package com.dp.appi.jsonp;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by xiaoji on 2015/3/24.
 */
@Component
public class JsonpView extends AbstractView {
    @Override
    protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //将model中的数据转换为JSON格式
        String json = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(map);

        //得到JSONP的callback函数名称
//        String callback = request.getParameter("callback");

        //将数据填充到callback，并回调
        StringBuffer buf = new StringBuffer();
//        buf.append(callback);
//        buf.append("(");
        buf.append(json.toString());
//        buf.append(");");

        response.setHeader("Content-type", "text/plain;charset=UTF-8");
        response.getOutputStream().write(buf.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();
    }
}
